import { useAppSelector } from '@/store'
import React, { memo, useCallback, useRef, useState } from 'react'
import type { ReactNode, ElementRef } from 'react'
import { BannerControl, BannerLeft, BannerRight, BannerWrapper } from './style';
import { shallowEqual } from 'react-redux';
import { Carousel } from 'antd';
interface IProps {
  children?: ReactNode,
}
const TopBanners: React.FC<IProps> = memo(() => {
  const [currentIndex, setCurrentIndex] = useState(0);

  // store 获取数据
  const { banners } = useAppSelector(state => {
    return {
      banners: state.recommend.banners
    }
  }, shallowEqual)
  // 背景图资源 图片模糊
  const bgImage = banners && banners[currentIndex] && banners[currentIndex].imageUrl + '?imageView&blur=40x20';
  // 轮播图,定义内部数据类型
  const bannerRef = useRef<ElementRef<typeof Carousel>>();
  const bannerChange = useCallback((from, to) => {
    setCurrentIndex(to)
  }, [])
  return (
    <BannerWrapper bgimage={bgImage} >
      <div className="banner w980">
        <BannerLeft >
          <Carousel autoplay effect='fade'
            ref={bannerRef} beforeChange={bannerChange}>
            {
              banners && banners.map((item, index) => {
                return (
                  <div key={index}>
                    <img src={item.imageUrl} alt={item.imageUrl} />
                  </div>
                )
              })
            }
          </Carousel>
        </BannerLeft>
        <BannerRight />
        <BannerControl >
          <button className="btn" onClick={() => bannerRef.current.prev()}></button>
          <button className="btn" onClick={() => bannerRef.current.next()}></button>
        </BannerControl>
      </div>


    </BannerWrapper>
  )
})
export default TopBanners